var config = require('config.js');
var appJs;
function S4() {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function guid() {
  return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

function objKeySort(obj) { //排序的函数
  let newkey = Object.keys(obj).sort();
  //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
  let newObj = {}; //创建一个新的对象，用于存放排好序的键值对
  for (let i = 0; i < newkey.length; i++) { //遍历newkey数组
    newObj[newkey[i]] = obj[newkey[i]]; //向新创建的对象中按照排好的顺序依次增加键值对
  }
  return newObj; //返回排好序的新对象
}

function timest() {
  let tmp = Math.round(new Date() / 1000);
  return tmp;
}

var uuid;
var token = "";
var _token_ = "";

function requestLoading(url, params, methods, hideLoad, hideToast, CallbackTimes = 0) {
  if (!appJs) {
    appJs = getApp();
  }
  // 自动补全域名
  if (url.indexOf('/') == 0) {
    url = config.web_url + url;
  }
  return new Promise(function(resolve, reject) {
    var method = methods || "POST";
    params = params || {};
    let platform = '';
    wx.getSystemInfo({
      success(res) {
        if (res.platform == "devtools") {
          platform = 'wxandriod'
        } else if (res.platform == "ios") {
          platform = 'wxios'
        } else if (res.platform == "android") {
          platform = 'wxandriod'
        }
        var openid=wx.getStorageSync('openid');
        var token = wx.getStorageSync('token') || '';
        var str=handleParam(params,token,platform,openid);
        wx.request({
          url: url,
          data: params,
          header: {
            'content-type': 'application/x-www-form-urlencoded',
            'TOKEN': token,
            'PLATFORM': platform,
            'openid':wx.getStorageSync('openid'),
            'version': '1.0.0'
          },
          method: method,
          success: function(res) {
              
            if (res.data.code === 401) {
              // 需要登录，清除默认存储的token
              wx.setStorageSync('token','');
            //   resolve(res.data);
              checkLogin(function (res) {
                  console.log(ret)
                if (res) {
                  _ajax(url, data, success, fail, complete)
                } else {
                  showError(res.data.msg, function () {
                    reject(res);
                  });
                }
              }); 
              return false;
            }
            resolve(res.data);
            if (res.data && res.data.msg) {
              toast(res.data.msg);
            }

           
          },
          fail: function(res) {
            console.log(res)
            typeof reject == "function" && reject(res)
          },
          complete: function(res) {
            // if(hideLoad){
            //   wx.hideLoading()
            // }
          },
        })
      }
    })
  })
}
function handleParam(data,token,platform,openid){
  if(!data){
    data={};
  }
  data.token = token;
  data.platform =platform;
  data.timestamp = timest();
  data.openid=openid
  return JSON.stringify(data);
}
function handleParam2(data,token,platform){
  if(!data){
    data={};
  }
  data.token = token;
  data.platform =platform;
  data.timestamp = timest();
  return JSON.stringify(data);
}
function rsaEncrypt(string) {
  string=encodeURIComponent(string);
  // 如果字符串过长，处理字符串
  try {
    var lt = "";
    var ct = "";
    //RSA每次加密117bytes，需要辅助方法判断字符串截取位置
    //1.获取字符串截取点
    var bytes = new Array();
    bytes.push(0);
    var byteNo = 0;
    var len, c;
    len = string.length;
    var temp = 0;
    for (var i = 0; i < len; i++) {
        c = string.charCodeAt(i);
        if (c >= 0x010000 && c <= 0x10FFFF) {
            byteNo += 4;
        } else if (c >= 0x000800 && c <= 0x00FFFF) {
            byteNo += 3;
        } else if (c >= 0x000080 && c <= 0x0007FF) {
            byteNo += 2;
        } else {
            byteNo += 1;
        }
        if ((byteNo % 117) >= 114 || (byteNo % 117) == 0) {
            if (byteNo - temp >= 114) {
                bytes.push(i);
                temp = byteNo;
            }
        }
    }
    //2.截取字符串并分段加密
    if (bytes.length > 1) {
        for (var i = 0; i < bytes.length - 1; i++) {
            var str;
            if (i == 0) {
                str = string.substring(0, bytes[i + 1] + 1);
            } else {
                str = string.substring(bytes[i] + 1, bytes[i + 1] + 1);
            }
            var t1 = encryptor.encrypt(str)
            ct += t1;
        }
        ;
        if (bytes[bytes.length - 1] != string.length - 1) {
            var lastStr = string.substring(bytes[bytes.length - 1] + 1);
            var t1 = encryptor.encrypt(lastStr);
            ct += t1;
        }
        return ct;
    }
    var t = encryptor.encrypt(string);
    return t;
  } catch (ex) {
      return false;
  }
}
function model(title,content,showCancel,callback,confirmColor,confirmText){
  wx.showModal({
    title: title || '提示',
    content: content,
    showCancel: showCancel,//是否显示取消按钮
    // cancelText:"否",//默认是“取消”
    // cancelColor:'skyblue',//取消文字的颜色
    confirmText:confirmText || "确定",
    confirmColor: confirmColor || "#5677fc",
    success: function (res) {
       if (res.cancel) {
        callback && callback(false)
       } else {
        callback && callback(true)
       }
    },
    fail: function (res) { },//接口调用失败的回调函数
    complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
  })
}

function showError(msg, callback) {
  wx.showModal({
    title: '提示',
    content: msg,
    showCancel: false,
    success: function (res) {
      callback && callback();
    }
  });
}

function showSuccess(msg, callback,icon="success") {


  wx.showToast({
    title: msg,
    icon: icon,
    success: function () {
      callback && (setTimeout(function () {
        callback();
      }, 1500));
    }
  });

}

function toast(msg) {
    setTimeout(function(){
        wx.showToast({
            title: msg,
            icon: 'none',
            duration:1500
          });
    },500)
 
}

function alert(msg) {
  wx.showModal({
    title: '提示',
    content: msg,
    showCancel: false,
    success(res) {
      if (res.confirm) {} else if (res.cancel) {}
    }
  })
}
/**
 * 检查登录状态
 * @param cb    回调函数
 */
function checkLogin(cb) {
  console.log('检查登录状态');
  if (!appJs) {
    appJs = getApp();
  }
  if (wx.getStorageSync('token')) {
    typeof cb == "function" && cb(true);
  } else {
    appJs.login(cb);
  }
}
/**
 * 检查是否完善资料
 * @param cb    回调函数
 */
function checkAuth(cb) {
  console.log('检查是否完善资料');
  checkLogin(function(){
    var userInfo=appJs.globalData.userInfo;
    if(userInfo.is_complete==0){
      // 跳转认证页面
      wx.navigateTo({
        url: '/pages/info/basic/index',
      })
    }else{
      typeof cb == "function" && cb()
    }
  });
}
/**
 * 检查是否实名认证
 * @param cb    回调函数
 */
function checkReal(cb) {
  checkAuth(function(){
    var userInfo=appJs.globalData.userInfo;
    if(userInfo.is_auth==0){
     
      typeof cb == "function" && cb(false)
    }else{
      typeof cb == "function" && cb(true)
    }
  });
}
// 分享当前页面（带参数）
function shareAppMessage() {
  var pages = getCurrentPages()
  var currentPage = pages[pages.length-1]
  var url = currentPage.route
  var options = currentPage.options

  let key_list = []
  for(let key in options) {
    key_list.push(`${key}=${options[key]}`)
  }

  return '/' + url + '?' + key_list.join('&')
}
//上传图片
var tempFilePaths;
var callback;
function chooseImg(num, cb) {
  num = num || 9;
  callback = cb || '';
  wx.chooseImage({
    count: num, // 默认9
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
    success: function (res) {
      // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
      tempFilePaths = res.tempFilePaths
      uploadImg(tempFilePaths);
    }
  });
}
function uploadImg(tempFilePaths) {
   
  var tempFile = tempFilePaths.shift(); //把数组的第一个元素从其中删除，并返回第一个元素的值
  var url = config.web_url + "/api/common/ossupload"
  wx.showLoading({
    title: '上传中...',
  });
  var token = wx.getStorageSync('token') || '';
  wx.uploadFile({
    url: url,
    filePath: tempFile,
    name: 'file',
    header: { 
      'content-type': 'application/x-www-form-urlencoded',
      'TOKEN': token,
      'PLATFORM': 'wxmini'
    },
    success: function (res) {
      var ret = JSON.parse(res.data);
      if (ret.code == 1) {
        var len = tempFilePaths.length;
        typeof callback == 'function' && callback(ret.data, len); //图片上传成功后置操作
        if (len > 0) {
          uploadImg(tempFilePaths);
        } else {
          wx.hideLoading();
        }
      } else {
        showError(ret.msg);
        console.log(ret.info);
        wx.hideLoading();
      }
    },
    fail: function (res) {
      wx.hideLoading();
    }
  })
}
//上传图片
var tempFilePaths;
var callback;
function chooseMedia(num, cb) {
  num = num || 9;
  callback = cb || '';
  wx.chooseVideo({
    sourceType: ['album','camera'],
    maxDuration: 60,
    camera: 'back',
    success: function (res) {
      // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
      uploadMedia(res.tempFilePath,res.size);
    }
  });
}
function uploadMedia(tempFile) {
  var url = config.web_url + "/api/common/ossupload"
  wx.showLoading({
    title: '上传中...',
  });
  var token = wx.getStorageSync('token') || '';
  wx.uploadFile({
    url: url,
    filePath: tempFile,
    name: 'file',
    header: { 
      'content-type': 'application/x-www-form-urlencoded',
      'TOKEN': token,
      'PLATFORM': 'wxmini'
    },
    success: function (res) {
      var ret = JSON.parse(res.data);
      if (ret.code == 1) {
        typeof callback == 'function' && callback(ret.data, 0); //图片上传成功后置操作
        wx.hideLoading();
      } else {
        showError(ret.msg);
        console.log(ret.info);
        wx.hideLoading();
      }
    },
    fail: function (res) {
      wx.hideLoading();
    }
  })
}
//微信支付
function wxpay(data, cb1, cb2) {
  wx.requestPayment({
    timeStamp: data.timeStamp,
    nonceStr: data.nonceStr,
    package: data.package,
    signType: data.signType,
    paySign: data.paySign,
    success: function (res) {
      if (res.errMsg == "requestPayment:ok") {
        typeof cb1 == "function" && cb1(res);
      }
    },
    fail: function (res) {
      if (res.errMsg == "requestPayment:fail cancel") {
        typeof cb2 == "function" && cb2(res);
      } else {
        alert("唤起微信支付失败！");
      }
    },
    complete: function (res) {
      if (res.errMsg == "requestPayment:cancel") {
        typeof cb2 == "function" && cb2(res);
      }
    }
  })
}
const dealWithRichText = originHtml => {
  let [html, imgUrls] = addRandomAndGetPreviewImageUrlsFromRichText(originHtml)
  const app = getApp()
  return app.towxml(html, 'html', {
    events: {
      // 给富文本绑定点击事件
      tap: event => {
        // console.log(event, "towxml event")
        // 只处理图片的点击事件
        if (event.currentTarget.dataset.data && event.currentTarget.dataset.data.attr && (event.currentTarget.dataset.data.attr.class == "h2w__img")) {
          // 传入图片地址，调用微信图片预览 API
        //   wx.previewImage({
        //     current: event.currentTarget.dataset.data.attr.src, // 当前显示图片的http链接
        //     urls: imgUrls
        //   })
        }
      }
    }
  })
}

/**
 * 从富文本中给图片链接添加 random 并且返回图片数组（加 random 防止重复图片预览打乱顺序）
 * @example let [html, imgUrls] = addRandomAndGetPreviewImageUrlsFromRichText(html)
 * @param {string} html 
 */
const addRandomAndGetPreviewImageUrlsFromRichText = html => {
  // 如果没有值的话，直接返回
  if (!html) {
    return html
  }

  let randomIndex = 0
  let imgUrls = []
  // 先匹配到 img 标签，放到 match 里
  html = html.replace(/<img[^>]*>/gim, function (match) {
    randomIndex++
    match = match.replace(/src="[^"]+"/gim, function (match) {
      // 再匹配到 src 标签 '"'
      let src = match.slice(5, -1) + "?random=" + randomIndex // 取到 src 里面的 url
      imgUrls.push(src)
      return 'src="' + src + '"'
    }).replace(/src='[^']+'/gim, function (match) {
      // 再匹配到 src 标签 "'"
      let src = match.slice(5, -1) + "?random=" + randomIndex
      return "src='" + src + "'"
    })

    return match
  })
  return [html, imgUrls]
}

/* 加载动画相关 */
const showLoading = () => {
  wx.showNavigationBarLoading()
  wx.showLoading({
    title: '加载中...',
  })
}
const hideLoading = () => {
  wx.hideLoading()
  wx.hideNavigationBarLoading()
}
const hideLoadingWithErrorTips = () => {
  hideLoading()
  wx.showToast({
    title: '加载失败...',
    icon: 'error',
    duration: 2000
  })
}
const formatFileSize =(limit)=> {
  var size = "";
  if(limit < 0.1 * 1024){                            //小于0.1KB，则转化成B
      size = limit.toFixed(2) + "B"
  }else if(limit < 0.1 * 1024 * 1024){            //小于0.1MB，则转化成KB
      size = (limit/1024).toFixed(2) + "KB"
  }else if(limit < 0.1 * 1024 * 1024 * 1024){        //小于0.1GB，则转化成MB
      size = (limit/(1024 * 1024)).toFixed(2) + "MB"
  }else{                                            //其他转化成GB
      size = (limit/(1024 * 1024 * 1024)).toFixed(2) + "GB"
  }

  var sizeStr = size + "";                        //转成字符串
  var index = sizeStr.indexOf(".");                    //获取小数点处的索引
  var dou = sizeStr.substr(index + 1 ,2)            //获取小数点后两位的值
  if(dou == "00"){                                //判断后两位是否为00，如果是则删除00
      return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
  }
  return size;
}
module.exports = {
  dealWithRichText: dealWithRichText,
  showLoading: showLoading,
  hideLoading: hideLoading,
  hideLoadingWithErrorTips: hideLoadingWithErrorTips,
  requestLoading: requestLoading,
  shareAppMessage: shareAppMessage,
  checkLogin:checkLogin,
  checkAuth:checkAuth,
  checkReal:checkReal,
  chooseImg:chooseImg,
  chooseMedia:chooseMedia,
  showError:showError,
  toast:toast,
  showSuccess:showSuccess,
  wxpay:wxpay,
  alert:alert,
  formatFileSize:formatFileSize
}
